package cn.edu.jxau.test;

import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 使用双List实现一个简单的映射集
 * @author 付大石
 */
public class SlowMap<K, V> extends AbstractMap<K, V> {
    
    public static void main(String[] args) {
        
        Map<Integer,String> map = new SlowMap<>();
        map.put(null,"A");
        map.put(1,"B");
        map.put(2,"C");
        System.out.println(map);
        map.put(null,"D");
        System.out.println(map);
        System.out.println(map.get(null));
    }

    private List<K> keyList;
    private List<V> valueList;

    public SlowMap() {
        keyList = new ArrayList<>();
        valueList = new ArrayList<>();
    }

    @Override
    public V get(Object key) {

        int index = keyList.indexOf(key); // 查找key所在的索引
        if (index >= 0) {
            return valueList.get(index);
        } else {
            return null;
        }
    }

    @Override
    public V put(K key, V value) {

        if (get(key) == null) { // 键值对不存在
            keyList.add(key);
            valueList.add(value);
            return null;
        } else {
            int index = keyList.indexOf(key);
            V oldValue = valueList.get(index);
            valueList.set(index, value);
            return oldValue;
        }
    }

    @Override
    public Set<Entry<K, V>> entrySet() {
        
        Set<Entry<K, V>> entrySet = new HashSet<>();
        Iterator<K> keyIterator = keyList.iterator();
        Iterator<V> valueIterator = valueList.iterator();
        while(keyIterator.hasNext()) {
            K key = keyIterator.next();
            V value = valueIterator.next();
            entrySet.add(new SimpleEntry<K,V>(key,value));
        }
        return entrySet;
    }
}
